package com.cqs.leetcode.backtrack;

import java.util.*;

/**
 * @author lixiaowen
 * @create 2019-12-18
 */
public class Permutations47 {

    private Set<String> prefixHandled = new HashSet<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        permutation(nums,0, new ArrayList<>(), new HashSet<>(), result,"");
        return result;
    }

    private void permutation(int[] nums, int level, List<Integer> list, Set<Integer> used, List<List<Integer>> result,final String prefix ){
        if (level == nums.length) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used.contains(i)) continue;
            String prefixNew = prefix + nums[i];
            if (prefixHandled.contains(prefixNew)) continue;
            list.add(nums[i]);
            used.add(i);
            permutation(nums, level + 1, list, used, result, prefixNew);
            //处理重复的元素
            prefixHandled.add(prefixNew);
            list.remove(list.size()-1);
            used.remove(i);
        }
    }

    public static void main(String[] args) {
        int size = 3;
        int[] nums = new int[size];
        for (int i = 0; i < nums.length; i++) {
//            nums[i] = i+1;
            nums[i] = 1+new Random().nextInt(size);
        }
        nums[0] = 1;
        nums[1] = 2;
        nums[2] = 1;
        Permutations47 permutations = new Permutations47();
        List<List<Integer>> lists = permutations.permuteUnique(nums);
        System.out.println(lists);
    }
}
